package com.aixin.project.servlet.admin;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;

import com.aixin.project.data.Expert;
import com.aixin.project.handler.ExpertHandler;
import com.aixin.project.util.Pagenation2;
import com.aixin.project.util.RequestUtil;

public class ExpertAdminServlet extends AdminServlet{
	Logger logger = Logger.getLogger(ExpertAdminServlet.class);
	@Override
	protected Template execute(HttpServletRequest request, HttpServletResponse response, Context ctx) {
		String method = request.getParameter("method");
		if("pwd".equals(method)){
            long ppwd = RequestUtil.getLong(request,"ppwd",-1);
			String password = RequestUtil.toMD5(request.getParameter("pwd1"));
			ExpertHandler.updatepwd(ppwd,password);
		}else if("status".equals(method)){
            long expid = RequestUtil.getLong(request,"expid",-1);
            int status = RequestUtil.getInt(request,"status"+expid,-1);
            if(expid!=-1 && status!=-1)
			    ExpertHandler.update(expid, status);
		}else if("create".equals(method)){
			String path = this.getServletContext().getRealPath("\\") + "images\\expert\\";//后面这个files目录
			String username = "";
			String pwd = "";
			String name = "";
			String education = "";
			String post = "";
			String intro = "";
			String gender = "";
			//DiskFileUpload du = new DiskFileUpload();
			if (ServletFileUpload.isMultipartContent(request)) {
				try{
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(4194304); // ��������ļ��ߴ磄1�7B
			List<FileItem> items = upload.parseRequest(request);// �õ����е��ļ�
			Iterator<FileItem> i = items.iterator();
			String[] file = null;
			FileItem fio = null;
			
			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (fi.isFormField()) {
					if("username".equals(fi.getFieldName())){
						username = fi.getString("utf-8");
					}else if("pwd".equals(fi.getFieldName())){
						pwd = RequestUtil.toMD5(fi.getString("utf-8"));
					}else if("name".equals(fi.getFieldName())){
						name = fi.getString("utf-8");
					}else if("education".equals(fi.getFieldName())){
						education = fi.getString("utf-8");
					}else if("post".equals(fi.getFieldName())){
						post = fi.getString("utf-8");
					}else if("intro".equals(fi.getFieldName())){
						intro = fi.getString("utf-8");
					}else if("gender".equals(fi.getFieldName())){
						gender = fi.getString("utf-8");
					}

				} else {
					//取得的是文件
					String filename = fi.getName();
					if(null != filename && !"".equals(filename)){
						file =  filename.split("\\.");
						fio = fi;
						//fi.write(new File(path +  filename));
					}
					}
			}
			Expert expert = new Expert();
			expert.setDescription(intro);
			expert.setEducation(education);
			expert.setGender(gender);
			expert.setName(name);
			expert.setPassword(pwd);
			expert.setPost(post);
			expert.setUsername(username);
			long id = ExpertHandler.addExpert(expert);
            ExpertHandler.clearExpertPageCache();
			if(null!=file)
				fio.write(new File(path + "e_"+id+"."+file[1]));
			
			}catch (Exception e) {
				logger.error("create expert: "+e.getMessage());
			}
			}
		}else if("del".equals(method)){
			String expid = request.getParameter("expid");
			ExpertHandler.removeExpert(expid);
            ExpertHandler.clearExpertPageCache();
		}else if("select".equals(method)){
			String status = request.getParameter("s");
			String name = request.getParameter("name");
			System.out.println("status: "+status);
			System.out.println("name: "+name);
		}
		
		
		
//		pagination
		int status = RequestUtil.getInt(request,"s",-1);
        int page = RequestUtil.getInt(request,"p",1);
        StringBuffer params = new StringBuffer();
        if(page!=1)
            params.append("&p=").append(page);
        if(status!=-1)
            params.append("&s=").append(params);
        if(params.length()>0)
            ctx.put("params",params.substring(1,params.length()));
        int psize = 10;
        List<Expert> list = ExpertHandler.getAdminExperts(page,psize,status);
        int count = (int)ExpertHandler.count(status);
        Pagenation2 pg = new Pagenation2(page,psize,count,list,"/admin/exp",params.toString());
        ctx.put("pg",pg);
		
        ctx.put("s", status);
		request.setAttribute("experts", list);
		request.setAttribute("navexpert", true);
		return getTemplate("bg/expert.vm");
	}

}
